package frame.system.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import frame.base.BaseService;
import frame.base.BootstrapTable;
import frame.base.Menu;
import frame.base.ZTree;
import frame.system.mapper.PermissionMapper;
import frame.system.qo.AuthQo;
import frame.system.to.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.util.StringUtil;

import java.util.*;


/**
 * Permission 模块服务类
 * <br>
 * @author PeiWentao
 * @since 2020-05-27 20:04
 */
@Service
public class PermissionService extends BaseService<Integer, Permission, AuthQo> {

	@Autowired
    private PermissionMapper permissionMapper;

    @Override
    protected Mapper<Permission> mainMapper() {
        return permissionMapper;
    }

    @Override
	public BootstrapTable<Permission> pageList(final AuthQo qo) {
        //分页查询
        Page<Permission> page = PageHelper.startPage(qo.page(), qo.size()).doSelectPage(() -> {
            // TODO 分页查询动态条件需要实现
            permissionMapper.pageList(qo);
        });
        return new BootstrapTable<Permission>(page.getTotal(),page.getResult());
	}

    @Override
    public Permission addSelective(Permission record) {
        if ("".equals(record.getShiro())){
            record.setShiro(null);
        }
        switch (record.getType()) {
            case Permission.TYPE_STATIC:
                record.setShiro(null);
                break;
            case Permission.TYPE_DIR:
                record.setShiro(null);
                record.setUrl(null);
                break;
            case Permission.TYPE_MENU:

                break;
            case Permission.TYPE_INTERFACE:

                break;
            default:
        }

        return super.addSelective(record);
    }

    @Override
    public int remove(Integer id) {
        // 逻辑删除 同时删除其孩子 删除与角色的关联
        return permissionMapper.remove(id) + permissionMapper.delete2Role(id);
    }

    /**
     * 查询所有的目录并转为ztree
     * @return
     */
    public ZTree allDirTree() {
        ZTree root = null;

        List<Permission> permissions = permissionMapper.allDirList();
        Map<Integer,ZTree> map = new HashMap<>();
        for (Permission permission : permissions) {
            map.put(permission.getId(),convert2Ztree(permission));
        }
        for (Integer id : map.keySet()) {
            ZTree tree = map.get(id);
            if (id == Permission.ROOT_ID) { //根节点
                root = tree;
            } else {
                Integer pid = tree.getPid();
                ZTree parent = map.get(pid);
                if (parent != null) {
                    parent.addChildren(tree);
                }
            }

        }
        return root;
    }
    /**
     * 查询所有的资源（目录，菜单，接口）并转为ztree
     * @return
     */
    public ZTree allPermissionTree() {
        ZTree root = null;

        List<Permission> permissions = permissionMapper.allPermissionList();
        Map<Integer,ZTree> map = new HashMap<>();
        for (Permission permission : permissions) {
            map.put(permission.getId(),convert2Ztree(permission));
        }
        for (Integer id : map.keySet()) {
            ZTree tree = map.get(id);
            if (id == Permission.ROOT_ID) { //根节点
                root = tree;
            } else {
                Integer pid = tree.getPid();
                ZTree parent = map.get(pid);
                if (parent != null) {
                    parent.addChildren(tree);
                }
            }

        }
        return root;
    }

    /**
     * 查询用户拥有的菜单
     * @param uid
     * @return
     */
    public Set<Menu> allPermissionMenu(Integer uid) {
        Set<Menu> menus = new TreeSet<>();
        List<Permission> permissions = permissionMapper.allPermissionListByUserId(uid);
        Map<Integer,Menu> map = new HashMap<>();
        for (Permission permission : permissions) {
            Menu menu = convert2Menu(permission);
            map.put(permission.getId(), menu);
            if (permission.getPid() == Permission.ROOT_ID)
                menus.add(menu);
        }
        for (Integer id : map.keySet()) {
            Menu menu = map.get(id);
            Menu parent =  map.get(menu.getPid());
            if ( parent != null) {
                parent.addSub(menu);
            }
        }
        return menus;
    }

    private ZTree convert2Ztree(Permission permission) {
        ZTree tree = new ZTree();
        tree.setId(permission.getId());
        tree.setPid(permission.getPid());
        Integer pid = permission.getPid();
        if ( pid == null )
            tree.setName("(" + permission.getId() + ")" + permission.getName() + "<->");
        else
            tree.setName("(" + permission.getId() + ")" + permission.getName() + "<" + pid + ">");
        tree.setIcon(permission.getType());
        tree.setSorting(permission.getSorting());
        return tree;
    }

    private Menu convert2Menu(Permission permission) {
        Menu menu = new Menu();
        menu.setId(permission.getId());
        menu.setPid(permission.getPid());
        menu.setSorting(permission.getSorting());
        menu.setName(permission.getName());
        if (!StringUtil.isEmpty(permission.getUrl())) {
            menu.setUrl(permission.getUrl());
        }
        return menu;
    }

    @Override
    protected void preAdd(Permission record) {
        super.preAdd(record);
        record.setId(null);
    }

    @Override
    protected Permission newInstanceT(Integer id) {
        return new Permission(id);
    }
}
